//
//  HRRecordBottomView.m
//  Hear
//
//  Created by mac on 2017/7/4.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "HRRecordBottomView.h"
#import "PulsingHaloLayer.h"
#import "EMCDDeviceManager.h"

@interface HRRecordBottomView ()
@property (assign, nonatomic) int duration;
@property (strong, nonatomic) NSTimer *timer;
@property (nonatomic, strong) PulsingHaloLayer *halo;


@property (nonatomic, strong) UILabel *textLabel;

@property (nonatomic,assign) BOOL showTime;
@property(nonatomic, strong)UIView *bottomView;
@property(nonatomic, copy)NSString *recordPath;
@property(nonatomic, assign)NSInteger aDuration;


@end
@implementation HRRecordBottomView

-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]){
        
        self.userInteractionEnabled = YES;
        
        
        UILabel *topLine = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.width, 1)];
        topLine.backgroundColor = CustomColor(240, 240, 240, 1);
        [self addSubview:topLine];
        
        //        self.backgroundColor = [UIColor grayColor];
        UIButton *centerImaegView = [[UIButton alloc] init];
        
        [centerImaegView setImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateNormal] ;
        
//        [centerImaegView setBackgroundImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateHighlighted] ;
        
        //        centerImaegView.backgroundColor = [UIColor grayColor];
        self.centerImaegView = centerImaegView;
        self.centerImaegView.userInteractionEnabled = NO;
        self.centerImaegView.frame = CGRectMake((self.width-100)/2, (self.height-100)/2, 100, 100);
        self.centerImaegView.layer.cornerRadius = self.centerImaegView.width/2;
        self.centerImaegView.layer.masksToBounds = YES;
        [self addSubview:centerImaegView];
        centerImaegView.tag = 1;
        self.centerImaegView.selected = NO;
        self.textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, kFullWidth, 13)];
        
        self.textLabel.textAlignment = NSTextAlignmentCenter;
        self.textLabel.textColor = CustomColor(73, 73, 73,1);
        self.textLabel.text = @"按住说话";
        [self addSubview:self.textLabel];
        self.textLabel.font = CustomUIFont(13);
        self.userInteractionEnabled = YES;
        
        self.showTime = YES;
        
        
//        UILabel *bottomLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,self.height-25, kFullWidth, 13)];
//        
//        bottomLabel.textAlignment = NSTextAlignmentCenter;
//        bottomLabel.textColor = CustomColor(73, 73, 73,1);
//        bottomLabel.text = @"手指上滑 取消发送";
//        [self addSubview:bottomLabel];
//        bottomLabel.font = CustomUIFont(13);
//        bottomLabel.userInteractionEnabled = YES;
        
        
        
        
        
        //        UIView *right = [[UIView alloc] initWithFrame:CGRectMake(centerImaegView.maxX+5, 0, self.width-centerImaegView.maxX-5, self.height)];
        //        right.backgroundColor = [UIColor grayColor];
        //        [self addSubview:right];
        
        
        UIButton *leftButton = [UIButton buttonWithType:0];
        [leftButton setImage:[UIImage imageNamed:@"试听"] forState:0];
        leftButton.frame = CGRectMake(15, self.textLabel.bottom, 50, 50);
        [self addSubview:(self.leftButton = leftButton)];
        leftButton.hidden = YES;
        leftButton.tag = 2;
//        [leftButton addTarget:self action:@selector(leftButtonRecordDragInside) forControlEvents:UIControlEventTouchDragInside];

        
        UIButton *rightButton = [UIButton buttonWithType:0];
        [rightButton setImage:[UIImage imageNamed:@"删除"] forState:0];
        rightButton.frame = CGRectMake(self.width-50-15, leftButton.top, 50, 50);
        [self addSubview:(self.rightButton = rightButton)];
        rightButton.hidden = YES;
        rightButton.tag = 3;
//        [rightButton addTarget:self action:@selector(leftButtonRecordDragInside) forControlEvents:UIControlEventTouchDragInside];
        
        
        UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, self.height-45, self.width, 45)];
        [self addSubview:(self.bottomView = bottomView)];
        bottomView.hidden = YES;
        
        UILabel *line1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, bottomView.width, 1)];
        line1.backgroundColor = CustomColor(240, 240, 240, 1);
        [bottomView addSubview:line1];
        
        
        UIButton *cancelButton = [UIButton buttonWithType:0];
        cancelButton.frame = CGRectMake(0,line1.bottom, bottomView.width/2, bottomView.height-line1.bottom);
        [cancelButton setTitle:@"取消" forState:0];
        [cancelButton setTitleColor:FirstTextColor forState:0];
        cancelButton.titleLabel.font = CustomUIFont(14);
        [cancelButton addTarget:self action:@selector(cancelButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:cancelButton];
        
        
        UILabel *line2 = [[UILabel alloc] initWithFrame:CGRectMake(bottomView.width/2, 0, 1, self.bottomView.height)];
        line2.backgroundColor = CustomColor(240, 240, 240, 1);
        [bottomView addSubview:line2];
        
        
        UIButton *senderButton = [UIButton buttonWithType:0];
        senderButton.frame = CGRectMake(cancelButton.right,cancelButton.top, cancelButton.width, cancelButton.height);
        [senderButton setTitle:@"发送" forState:0];
        [senderButton setTitleColor:MainColor forState:0];
        senderButton.titleLabel.font = CustomUIFont(14);
        [senderButton addTarget:self action:@selector(senderButtonClick) forControlEvents:UIControlEventTouchUpInside];
        [bottomView addSubview:senderButton];
    }
    
    return self;
    
}




-(void)startAnima
{
    self.leftButton.hidden = NO;
    self.rightButton.hidden = NO;
    if(![self.halo superlayer]){
        [self.centerImaegView.superview.layer insertSublayer:self.halo below:self.centerImaegView.layer];
    }
    
}

-(void)stopAnima
{
    self.leftButton.hidden = YES;
    self.rightButton.hidden = YES;
    if([self.halo superlayer]){
        [self.halo removeFromSuperlayer];
    }
    
    
}

-(PulsingHaloLayer *)halo
{
    if(!_halo){
        
        PulsingHaloLayer *halo = [PulsingHaloLayer layer];
        
        halo.backgroundColor = MainColor.CGColor;
        halo.radius = 80;//(self.height-16)/2;
        halo.position = self.centerImaegView.center;
        
        halo.haloLayerNumber = 4;
        _halo = halo;
    }
    return _halo;
}





// 录音按钮按下
-(void)recordButtonTouchDown
{
    [self startAnima];
    [self startTimer];
    
    // 需要根据声音大小切换recordView动画
    _textLabel.text = [self formattedTime:_duration] ;
    
    
    
    
}
// 手指在录音按钮内部时离开
-(void)recordButtonTouchUpInside
{
    
    [self stopAnima];
    
    [self stopTimer];
    _textLabel.text = @"按住说话";
    
    
}
// 手指在录音按钮外部时离开
-(void)recordButtonTouchUpOutside
{
    [self stopAnima];
    [self stopTimer];
    _textLabel.text = @"按住说话";
    
    
}
// 手指移动到录音按钮内部
-(void)recordButtonDragInside
{
    //    _textLabel.text = @"手指往上滑取消发送";
    _textLabel.text = [self formattedTime:_duration];
    
}

// 手指移动到录音按钮外部
-(void)recordButtonDragOutside
{
    //    self.showTime = NO;
    //
    //    _textLabel.text = @"松开手指取消发送";
    
}


#pragma mark - RecordTimer

- (void)startTimer {
    _duration = 0;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(increaseRecordTime) userInfo:nil repeats:YES];
}

- (void)stopTimer {
    if (_timer) {
        [_timer invalidate];
        self.timer = nil;
    }
}

- (void)increaseRecordTime {
    _duration++;
    if(self.showTime){
        _textLabel.text = [self formattedTime:_duration];
        
    }
}

- (NSString *)formattedTime:(int)duration {
    
    self.showTime = YES;
    
    return [NSString stringWithFormat:@"%02d:%02d", duration / 60, duration % 60];
}


#pragma mark - touch

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];
    //    _touchState = AudioRecordViewTouchStateInside;
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    
    
    if(self.centerImaegView.userInteractionEnabled){
        return;
    }
    
    [super touchesMoved:touches withEvent:event];

    
    UITouch *touch = [touches anyObject];
    UIView *hitView=[self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];

    CGPoint point = [touch locationInView:self.centerImaegView];
    if (CGRectContainsPoint(self.centerImaegView.bounds, point)){
        DDLog(@"================center");
        if (self.leftButton.hidden){
            if ([self.delegate respondsToSelector:@selector(didStartRecordingVoiceActionFromRecordBottomView)])
            {
                [self.delegate didStartRecordingVoiceActionFromRecordBottomView];
            }
            [self recordButtonTouchDown];
        }
        
        
        
    }else if(hitView.tag == 2){
        DDLog(@"================left");
        self.textLabel.text = @"松开试听";
    }else if(hitView.tag == 3){
        DDLog(@"================right");
        self.textLabel.text = @"松开取消";
    }else{
        
    }
    
    //    BOOL touchInside = [self pointInside:[touch locationInView:self] withEvent:nil];
    //    BOOL touchStateChanged = NO;
    ////    if (_touchState == AudioRecordViewTouchStateInside && !touchInside) {
    //        _touchState = AudioRecordViewTouchStateOutside;
    //        touchStateChanged = YES;
    //    }
    //    else if (_touchState == AudioRecordViewTouchStateOutside && touchInside) {
    //        _touchState = AudioRecordViewTouchStateInside;
    //        touchStateChanged = YES;
    //    }
    //    if (touchStateChanged) {
    //        if (_delegate && [_delegate respondsToSelector:@selector(recordView:touchStateChanged:)]) {
    //            [_delegate recordView:self touchStateChanged:_touchState];
    //        }
    //    }
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    if(self.centerImaegView.userInteractionEnabled){
        return;
    }
    
    UITouch *touch = [touches anyObject];
    
    CGPoint point = [touch locationInView:self.centerImaegView];
    
    UIView *hitView=[self hitTest:[[touches anyObject] locationInView:self] withEvent:nil];

    if (hitView.tag == 1){
        DDLog(@"================center");
        [self recordButtonTouchUpOutside];
        
        WeakSelf
        [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
            if (!error) {
                weakSelf.recordPath = recordPath;
                weakSelf.aDuration = aDuration;
                if ([weakSelf.delegate respondsToSelector:@selector(didFinishRecoingVoiceActionFromRecordBottomView:andDuration:)])
                {
                    [weakSelf.delegate didFinishRecoingVoiceActionFromRecordBottomView:weakSelf.recordPath andDuration:weakSelf.aDuration];
                }
            }
            else {
                
            }
        }];
       

    }else if(hitView.tag == 2){
        DDLog(@"================left");
        self.bottomView.hidden = NO;
        self.centerImaegView.userInteractionEnabled = YES;

        WeakSelf
        [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
            if (!error) {
                weakSelf.recordPath = recordPath;
                weakSelf.aDuration = aDuration;
            }
            else {
                
            }
        }];
        
        
        
        [self.centerImaegView setImage:[UIImage imageNamed:@"聊天录制_播放"] forState:0];
        [self.centerImaegView setImage:[UIImage imageNamed:@"聊天录制_暂停"] forState:UIControlStateSelected];
        [self.centerImaegView addTarget:self action:@selector(playVoiceClick) forControlEvents:UIControlEventTouchUpInside];
        [self stopAnima];
        [self stopTimer];
        
        
        
        

    }else if(hitView.tag == 3){
        DDLog(@"================right");
        
        [self recordButtonTouchUpOutside];
        
        if ([self.delegate respondsToSelector:@selector(didCancelRecordingVoiceActionFromRecordBottomView)])
        {
            [self.delegate didCancelRecordingVoiceActionFromRecordBottomView];
        }
    }else{
         DDLog(@"================other");
        if (self.leftButton.hidden) return;
        [self recordButtonTouchUpOutside];
        WeakSelf
        [[EMCDDeviceManager sharedInstance] asyncStopRecordingWithCompletion:^(NSString *recordPath, NSInteger aDuration, NSError *error) {
            if (!error) {
                weakSelf.recordPath = recordPath;
                weakSelf.aDuration = aDuration;
                if ([weakSelf.delegate respondsToSelector:@selector(didFinishRecoingVoiceActionFromRecordBottomView:andDuration:)])
                {
                    [weakSelf.delegate didFinishRecoingVoiceActionFromRecordBottomView:self.recordPath andDuration:weakSelf.aDuration];
                }
            }
            else {
                
            }
        }];
       
    }
    [super touchesEnded:touches withEvent:event];

}


- (void)playVoiceClick{
    self.centerImaegView.selected = !self.centerImaegView.isSelected;
    if (self.centerImaegView.isSelected){
//        [self addPlayTime];
        [[EMCDDeviceManager sharedInstance] asyncPlayingWithPath:self.recordPath completion:^(NSError *error) {
            if (!error){
                self.centerImaegView.selected = NO;
            }
        }];
    }else{
        [[EMCDDeviceManager sharedInstance] stopPlaying];
    }
}


- (void)cancelButtonClick{
    

//    [self stopTimer];
    [[EMCDDeviceManager sharedInstance] cancelCurrentRecording];
    [self.centerImaegView setImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateNormal] ;
    [self.centerImaegView setImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateSelected] ;

    
    self.centerImaegView.userInteractionEnabled = NO;

    [self.centerImaegView removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];
    [self recordButtonTouchUpOutside];
    self.bottomView.hidden = YES;
}

- (void)senderButtonClick{
//    [self stopTimer];


    
    [self.centerImaegView setImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateNormal] ;
    [self.centerImaegView setImage:[UIImage imageNamed:@"record_logo"] forState:UIControlStateSelected] ;

    self.centerImaegView.userInteractionEnabled = NO;

    [self.centerImaegView removeTarget:self action:NULL forControlEvents:UIControlEventTouchUpInside];

    self.bottomView.hidden = YES;
    if ([self.delegate respondsToSelector:@selector(didFinishRecoingVoiceActionFromRecordBottomView:andDuration:)])
    {
        [self.delegate didFinishRecoingVoiceActionFromRecordBottomView:self.recordPath andDuration:self.aDuration];
    }
}


//- (void)addPlayTime{
//    _duration = 0;
//
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(playTimerChange) userInfo:nil repeats:YES];
//}
//
//- (void)playTimerChange{
//    _duration ++;
//    _textLabel.text = [self formattedTime:self.aDuration-_duration];
//    if (![[EMCDDeviceManager sharedInstance] isPlaying]){
//        self.centerImaegView.selected = NO;
//    }
//
//}






@end
